﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Serialization;
using Common.Log;
using ExtBusiness.CommonBusiness;
using ExtBusiness.Model;
using WF_Business;
using Common;
using WF_DataAccess;

namespace ExtBusiness.Interface
{
    public class SerialBLL
    {
        public static SerialBLL Instance { get { return new SerialBLL(); } }
        /// <summary>
        ///  获取审批数据
        /// </summary>
        /// <param name="appid"></param>
        /// <returns></returns>
        private static DataTable GetApprovalData(string appid)
        {
            var strSql = string.Format(@"select a.appid,
       g.iid,
       c.单位名称,
       c.申请人代码 as 单位代码,
       c.用户代码   as 单位代码,
       c.详细地址1  as 单位地址,
       c.经办人姓名,
       c.身份证号码,
       c.联系电话1  as 经办人电话, 
       c.电子邮箱1 as 经办人邮箱,   
       c.机构名称 as 保密单位名称,
       c.详细地址2 as 保密单位地址,
       c.联系电话2 as 保密人员联系电话,
       c.人员姓名 as 保密人姓名,
       c.机关名称 as 证明单位名称,
       c.详细地址3 as 证明单位地址,
       c.联系电话3 as 证明人员联系电话,
       c.承办人姓名 as 证明人姓名,
       c.使用目的,
       c.项目名称,
       c.zmhbh as 应用领域,
       c.批准单位名称,
       nvl2(c.单位性质1, '国家机关、', '') || nvl2(c.单位性质2, '事业、', '') ||
       nvl2(c.单位性质3, '企业、', '') || nvl2(c.单位性质4, '军队、', '') ||
       nvl2(c.单位性质5, '其他、', '') 单位性质,
       (select slbh from ut_测绘成果申请使用受理通知书 t where t.iid = c.iid) as 受理文号,
       (select createtime  from st_instance b where b.iid = g.iid) as 受理时间, 
       (select createtime  from st_instance b where b.iid = g.iid) as 批准时间,  
       c.jdsbh as 批准文号,
       c.批准文号 批准文件号,
(select (case when h.申请材料4='1' then '无偿提供' else '有偿提供' end ) from UT_测绘成果审批表 h where h.iid=c.iid) tgfs,
       case  
         when ((select status from st_instance b where b.iid = g.iid)=2 and c.jdsbh is not null)   then
          '审核通过'
         when ((select status from st_instance b where b.iid = g.iid)=2 and c.jdsbh is  null)   then
          '审核不通过'
         else
          '正在办理'
       end 办理结果
  from xt_submit_info        g,
       ut_测绘成果使用申请表 c,
       xt_appid_iid          a
 where g.iid = c.iid
   and g.iid = a.iid
   and a.appid = '{0}'", appid);
            DataTable dtTemp;
            SysParams.OAConnection().RunSql(strSql, out dtTemp);
            return dtTemp;
        }

        ///// <summary>
        ///// 根据订单号获取审批结果
        ///// </summary>
        ///// <param name="appid"></param>
        ///// <returns></returns>
        //public string GetApprovalResult(string appid)
        //{
        //    var dtTemp = GetApprovalData(appid);
        //    var builder = new StringBuilder();
        //    builder.AppendFormat("<RecordInfo Count='{0}'>", dtTemp.Rows.Count);
        //    dtTemp.Rows.Cast<DataRow>().ToList().ForEach(row =>
        //    {
        //        builder.AppendFormat("<Trans><AppId>{0}</AppId>", row["appid"].ToString());
        //        builder.AppendFormat("<AppUnitName>{0}</AppUnitName>", row["单位名称"].ToString());
        //        builder.AppendFormat("<AppUnitCode>{0}</AppUnitCode>", row["单位代码"].ToString());
        //        builder.AppendFormat("<AppUnitAddress>{0}</AppUnitAddress>", row["单位地址"].ToString());
        //        builder.AppendFormat("<JbrName>{0}</JbrName>", row["经办人姓名"].ToString());
        //        builder.AppendFormat("<JbrPersonId>{0}</JbrPersonId>", row["身份证号码"].ToString());
        //        builder.AppendFormat("<BMUnitName>{0}</BMUnitName>", row["保密单位名称"].ToString());
        //        builder.AppendFormat("<BMUnitAddress>{0}</BMUnitAddress>", row["保密单位地址"].ToString());
        //        builder.AppendFormat("<BMPhone>{0}</BMPhone>", row["保密人员联系电话"].ToString());
        //        builder.AppendFormat("<BMPersonName>{0}</BMPersonName>", row["保密人姓名"].ToString());
        //        builder.AppendFormat("<ZMUnitName>{0}</ZMUnitName>", row["证明单位名称"].ToString());
        //        builder.AppendFormat("<ZMUnitAddress>{0}</ZMUnitAddress>", row["证明单位地址"].ToString());
        //        builder.AppendFormat("<ZMPhone>{0}</ZMPhone>", row["证明人员联系电话"].ToString());
        //        builder.AppendFormat("<ZMPersonName>{0}</ZMPersonName>", row["证明人姓名"].ToString());
        //        builder.AppendFormat("<Purpose>{0}</Purpose>", row["使用目的"].ToString());
        //        builder.AppendFormat("<ProjectName>{0}</ProjectName>", row["项目名称"].ToString());
        //        builder.AppendFormat("<ApproveDept>{0}</ApproveDept>", row["批准单位名称"].ToString());
        //        builder.AppendFormat("<AppDeptType>{0}</AppDeptType>", row["单位性质"].ToString().TrimEnd('、'));
        //        builder.AppendFormat("<ApproveNo>{0}</ApproveNo>", row["批准文号"].ToString());
        //        builder.AppendFormat("<AppResult>{0}</AppResult></Trans>", row["办理结果"].ToString());
        //    });
        //    builder.Append("</RecordInfo>");
        //    return builder.ToString();
        //}
        /// <summary>
        /// 根据订单号获取审批结果
        /// </summary>
        /// <param name="appid"></param>
        /// <returns></returns>
        public string GetApprovalResult(string appid)
        {
            var dtTemp = GetApprovalData(appid);
            var model = new RecordInfo { Count = dtTemp.Rows.Count };
            dtTemp.Rows.Cast<DataRow>().ToList().ForEach(row =>
            {
                model.Trans = new Trans
                {
                    AppId = row["appid"].ToString(),
                    Iid = row["iid"].ToString(),
                    AppUnitName = row["单位名称"].ToString(),
                    AppUnitCode = row["单位代码"].ToString(),
                    AppUnitAddress = row["单位地址"].ToString(),
                    JbrName = row["经办人姓名"].ToString(),
                    JbrEmail = row["经办人邮箱"].ToString(),
                    JbrPersonId = row["身份证号码"].ToString(),
                    JbrTel = row["经办人电话"].ToString(),
                    BMUnitName = row["保密单位名称"].ToString(),
                    BMUnitAddress = row["保密单位地址"].ToString(),
                    BMPhone = row["保密人员联系电话"].ToString(),
                    BMPersonName = row["保密人姓名"].ToString(),
                    ZMUnitName = row["证明单位名称"].ToString(),
                    ZMUnitAddress = row["证明单位地址"].ToString(),
                    ZMPhone = row["证明人员联系电话"].ToString(),
                    ZMPersonName = row["证明人姓名"].ToString(),
                    Purpose = row["使用目的"].ToString(),
                    ProjectName = row["项目名称"].ToString(),
                    YYLY = row["应用领域"].ToString(),
                    ApproveDept = row["批准单位名称"].ToString(),
                    AppDeptType = row["单位性质"].ToString().TrimEnd('、'),
                    SLWH = row["受理文号"].ToString(),
                    SLSJ = row["受理时间"].ToString(),
                    PZSJ = row["批准时间"].ToString(),
                    ApproveNo = row["批准文号"].ToString(),
                    Tgfs = row["tgfs"].ToString(),
                    AppResult = row["办理结果"].ToString()
                };
            });
            var resultStr = model.T2Xml();
            return resultStr;
        }

        /// <summary>
        /// 更新成果信息
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="userid"></param>
        /// <param name="iid"></param>
        /// <param name="summary"></param>
        /// <returns></returns>
        private static Tuple<bool, string> UpdateRsInfo(string appId, string userid, string iid, string summary)
        {
            var rsName = new StringBuilder();
            var rsType = new StringBuilder();
            try
            {
                //var list = summary.Json2T<List<SecretResultInfo>>();

                var list = JsonOperation.GetObjectFromJson<List<SecretResultInfo>>(summary);
                list.ForEach(t =>
                {
                    rsName.Append(string.Concat(t.RsName, "、"));

                    string strTemp = "";
                    //strTemp = string.Concat(t.ApplyType, "|", t.RsRange, "|", t.RsJd, "|", t.RsCount, "\r\n");

                    if (t.RsName.IndexOf("水准点") > 0 || t.RsName.IndexOf("三角点") > 0 || t.RsName.IndexOf("GNSS") > 0)
                    {
                        strTemp = string.Format("{0}所在图幅:{1}\r\n", t.RsName,t.RsRange);
                    }
                    else
                    {
                        string strDanWei = t.RsName.IndexOf("DLG") > 0 || t.RsName.IndexOf("地形图") > 0 ? "幅" : "";
                        strTemp = string.Format("{0}({1}{2}):{3}\r\n", t.RsName, t.RsCount, strDanWei, t.RsRange);
                    }
                    rsType.Append(strTemp);
                });

                string strAllTypeInfo = rsType.ToString();

                if(rsType.ToString().Length>1000)//如果超过特定长度则简化处理
                {
                    rsName.Clear(); rsType.Clear();
                    list.ForEach(t =>
                    {
                        rsName.Append(string.Concat(t.RsName, "、"));

                        string strTemp = "";
                        string strDanWei = t.RsName.IndexOf("DLG") > 0 || t.RsName.IndexOf("地形图") > 0 ? "幅" : "";
                        //if (t.RsName.IndexOf("水准点") > 0 || t.RsName.IndexOf("三角点") > 0 || t.RsName.IndexOf("GNSS") > 0)
                        //{
                        //    strDanWei = "所在图幅：";
                        //}
                        strTemp = string.Format("{0}({1}{2})\r\n", t.RsName, t.RsCount, strDanWei);
                        rsType.Append(strTemp);
                    });

                    rsType.Append("申请范围详见附件。");
                }
                var result = UpdateRsData(appId, userid, iid, rsName.ToString().TrimEnd('、'), rsType.ToString(), strAllTypeInfo);
                return result;
            }
            catch (Exception ex)
            {
                LogManage.addLogErr("Tuple<bool, string> UpdateRsInfo", appId + " " + userid + " " + iid + " " + summary + " " + ex.Message);
                return Tuple.Create(false, ex.Message);
            }
        }

        private static Tuple<bool, string> UpdateRsData(string appId, string userid, string iid, string rsName, string rsType, string strAllTypeInfo)
        {
            var ida = SysParams.OAConnection(true);
            try
            {
                var strSql = string.Format(" select count(*) from UT_测绘成果使用申请表 where iid='{0}'", iid);
                if (ida.GetValue(strSql) == "0")
                {
                    strSql = string.Format("insert into UT_测绘成果使用申请表 (iid,input_index) values ('{0}','0')", iid);                
                }
                else
                {
                    strSql = string.Format("update UT_测绘成果使用申请表  set 成果资料名称='{0}',种类='{1}' where iid='{2}'", rsName, rsType, iid);                    
                }
                ida.RunSql(strSql);

                strSql = string.Format("select count(*) from UT_SMCG_DDGY where iid='{0}'", iid);
                if (ida.GetValue(strSql) == "0")
                {
                    strSql = string.Format("insert into UT_SMCG_DDGY (iid,DDGYXX) values ('{0}',:gyxx)", iid);
                }
                else
                {
                    strSql = string.Format("update UT_SMCG_DDGY set DDGYXX=:gyxx where iid='{0}'", iid);
                }
                IDataParameter[] iDataPrams = DataFactory.GetParameter(DataFactory.DefaultDbType, 1);
                iDataPrams[0].ParameterName = "gyxx";
                iDataPrams[0].DbType = DbType.AnsiString;
                iDataPrams[0].Value = strAllTypeInfo;
                ida.RunSql(strSql, ref iDataPrams);  

                strSql = string.Format("select count(*) from xt_appid_iid where iid='{0}'", iid);
                if (ida.GetValue(strSql) == "0")
                {
                    strSql = string.Format("insert into xt_appid_iid (iid,appid,userid) values ('{0}','{1}','{2}')", iid, appId, userid);
                }
                else
                {
                    strSql = string.Format("update xt_appid_iid set appid='{1}',userid='{2}' where iid='{0}'", iid, appId, userid);
                }
                ida.RunSql(strSql);             

                ida.Close(true);
                return Tuple.Create(true, string.Empty);
            }
            catch (Exception ex)
            {
                ida.Close(false);
                LogManage.addLogErr("UpdateRsData", appId + " " + userid + " " + iid + " " + rsName + " " + rsType + " " + ex.Message);
                return Tuple.Create(false, ex.Message);
            }
        }
        /// <summary>
        /// 返回xml字符串
        /// </summary>
        /// <returns></returns>
        public string GetXmlStr(string appId, string userid, string iid, string summary)
        {
            var result = UpdateRsInfo(appId, userid, iid, summary);
            var builder = new StringBuilder();
            builder.Append("<RecordInfo><Trans>");
            if (result.Item1)
            {
                var url = ConfigurationManager.AppSettings["SecretBaseUrl"];
                url = string.Concat(url, "?iid=", iid, "&flowname=", HttpUtility.UrlEncode("国家涉密基础测绘成果使用申报"), "&tabsIndex=1");
                builder.AppendFormat("<Url>{0}</Url>", url);
                builder.AppendFormat("<Userid>{0}</Userid>", userid);
                builder.AppendFormat("<Iid>{0}</Iid>", iid);
            }
            else
            {
                builder.AppendFormat("<IsSuccess>{0}</IsSuccess>", "false");
                builder.AppendFormat("<ErrMsg>{0}</ErrMsg>", result.Item2);
            }
            builder.Append("</Trans></RecordInfo>");
            return builder.ToString();
        }

        public string DeleteInfo(string iid)
        {
            var ida = SysParams.OAConnection(true);
            try
            {
                var strSql = string.Format("delete from UT_测绘成果使用申请表 where iid='{0}' and exists (select submitflag from xt_submit_info where iid='{0}' and (submitflag='0' or submitflag='-1'))", iid);
                ida.RunSql(strSql);
                strSql = string.Format(" delete from ut_国家测绘局地图审核申请表 where iid = '{0}' and exists (select submitflag from xt_submit_info where iid='{0}' and (submitflag='0' or submitflag='-1'))", iid);
                ida.RunSql(strSql);

                strSql = string.Format("delete from xt_serial_attachment where (地信申报信息ID = '{0}' or APPDATAID = '{0}') and exists (select submitflag from xt_submit_info where iid='{0}' and (submitflag='0' or submitflag='-1'))", iid);
                ida.RunSql(strSql);

                strSql = string.Format("delete from xt_submit_info where iid = '{0}' and (submitflag='0' or submitflag='-1')", iid);
                ida.RunSql(strSql);

                ida.Close(true);
                return "1".T2Xml();
            }
            catch (Exception ex)
            {
                ida.Close(false);
                LogManage.addLogErr("DeleteInfo", iid + ex.Message);
                return "0".T2Xml();
            }
        }
    }
}
